package com.luyou.awt.event;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;


/**
 * 为窗口添加监听器
 * 使用监听适配器无需实现所有事件方法
 */
public class WindowListenerTest {

    private JFrame frame = new JFrame("测试");
    private TextArea ta = new TextArea();

    public void init(){
        frame.addWindowListener(new MyListener());
        frame.add(ta);
        frame.pack();
        frame.setVisible(true);
    }


    private class MyListener implements WindowListener {
        @Override
        public void windowOpened(WindowEvent e) {
            ta.append("窗口初次被打开\n");
        }

        @Override
        public void windowClosing(WindowEvent e) {
            ta.append("用户关闭窗口\n");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
            System.exit(0);
        }

        @Override
        public void windowClosed(WindowEvent e) {
            ta.append("窗口被成功关闭\n");
        }

        @Override
        public void windowIconified(WindowEvent e) {
            ta.append("窗口最小化\n");
        }

        @Override
        public void windowDeiconified(WindowEvent e) {
            ta.append("窗口被恢复\n");
        }

        @Override
        public void windowActivated(WindowEvent e) {
            ta.append("窗口被激活\n");
        }

        @Override
        public void windowDeactivated(WindowEvent e) {
            ta.append("窗口失去焦点\n");
        }
    }

    public static void main(String[] args) {
        new WindowListenerTest().init();
    }
}
